"""Centralised configuration helpers for the RAG demo."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

from pydantic import Field
from pydantic_settings import BaseSettings


BASE_DIR = Path(__file__).resolve().parent
DEFAULT_SOURCE_DIR = BASE_DIR / "data" / "source_documents"
DEFAULT_PERSIST_DIR = BASE_DIR / "storage" / "chroma_db"


class RAGSettings(BaseSettings):
    """Application settings driven by environment variables or .env file."""

    api_key: Optional[str] = Field(default="sk-pdfifkpjdlxvyvgkerbluaotktpznsmpbcvskjauotenxgvz", alias="OPENAI_API_KEY")
    api_base: Optional[str] = Field(default="https://api.siliconflow.cn/v1/", alias="OPENAI_API_BASE")
    llm_model: str = Field(default="Qwen/Qwen2.5-7B-Instruct", alias="RAG_LLM_MODEL")
    embed_model: str = Field(default="BAAI/bge-m3", alias="RAG_EMBED_MODEL")
    temperature: float = Field(default=0.1, alias="RAG_TEMPERATURE")
    chunk_size: int = Field(default=500, alias="RAG_CHUNK_SIZE")
    chunk_overlap: int = Field(default=100, alias="RAG_CHUNK_OVERLAP")
    search_k: int = Field(default=4, alias="RAG_SEARCH_K")
    persist_dir: Path = Field(default=DEFAULT_PERSIST_DIR, alias="RAG_PERSIST_DIR")
    source_dir: Path = Field(default=DEFAULT_SOURCE_DIR, alias="RAG_SOURCE_DIR")
    optimization_base_url: Optional[str] = Field(
        default="http://localhost:3000",
        alias="RAG_OPTIMIZATION_BASE_URL",
        description="Base URL for diting optimization service",
    )
    optimization_token: Optional[str] = Field(
        default=None,
        alias="RAG_OPTIMIZATION_TOKEN",
        description="Bearer token for optimization service",
    )
    optimization_timeout: float = Field(
        default=30.0,
        alias="RAG_OPTIMIZATION_TIMEOUT",
        description="HTTP timeout (seconds) for optimization requests",
    )

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        populate_by_name = True
        arbitrary_types_allowed = True
        extra = "ignore"

    def ensure_directories(self) -> None:
        """Create local folders when they are missing."""
        self.persist_dir.mkdir(parents=True, exist_ok=True)
        self.source_dir.mkdir(parents=True, exist_ok=True)


def load_settings() -> RAGSettings:
    """Convenience helper used across the scripts."""
    settings = RAGSettings()
    settings.ensure_directories()
    return settings
